/*
 *基于时间线触发的定时器 
*/

#ifndef __timerManager_H__
#define __timerManager_H__

#include <iostream>
#include <functional>
#include <chrono>
#include <map>

class Timer
{
public:
    Timer(int32_t repeat = 1);
    ~Timer();

    template<typename F, typename... Arg>
    void CallBack(uint32_t milliseconds, F&& f, Arg&&... args);

    void OnTimer();

    uint64_t GetTime() { return m_time; }

    int32_t GetRepeat() { return m_repeat; }
    
    //返回当前时间戳
    static uint64_t Now();

private:
    uint64_t m_time;    //定时器执行的时间点-毫秒
    std::function<void()> m_func;
    uint32_t m_period;   //定时器触发的周期-毫秒
    int32_t  m_repeat;   //定时器触发的次数 -1 表示无限触发
};

template<typename F, typename... Arg>
void Timer::CallBack(uint32_t milliseconds, F&& f, Arg&&... args)
{
    m_period = milliseconds;
    m_func = std::bind(std::forward<F>(f), std::forward<Arg>(args)...);
}


class TimerManager
{
public:
    TimerManager() = default;
    ~TimerManager() = default;

    //添加定时任务
    //milliseconds  触发间隔
    //f  aggs       回调函数和回调函数参数
    //repeat        定时器触发次数，-1 为无限触发
    template<typename F, typename... Args>
    void schedule(uint32_t milliseconds,int32_t repeat, F&& f, Args&&... aggs);

    //管理定时任务
    void UpDate();

    uint32_t GetTimerSize() { return m_timers.size(); }
private:
    std::multimap<uint64_t, Timer> m_timers; //first:定时器运行的时间点 secnd:定时器
};


//添加定时任务
template<typename F, typename... Args>
void TimerManager::schedule(uint32_t milliseconds,int32_t repeat, F&& f, Args&&... aggs)
{
    Timer t(repeat);
    t.CallBack(milliseconds, std::forward<F>(f), std::forward<Args>(aggs)...);
    m_timers.insert(std::make_pair(t.GetTime(), t));
}

#endif
